package org.example.download;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.URL;

public class DownloadThread implements Runnable {
    private int threadId;
    private long startIndex;
    private long endIndex;
    private String url;
    private String filePath;

    public DownloadThread(int threadId, long startIndex, long endIndex, String url, String filePath) {
        this.threadId = threadId;
        this.startIndex = startIndex;
        this.endIndex = endIndex;
        this.url = url;
        this.filePath = filePath;
    }

    @Override
    public void run() {
        try {
            URL urlObj = new URL(this.url);
            BufferedInputStream bis = new BufferedInputStream(urlObj.openStream());
            RandomAccessFile raf = new RandomAccessFile(filePath, "rw");
            raf.seek(startIndex);

            byte[] buffer = new byte[1024];
            int len;
            long downloaded = 0;
            while ((len = bis.read(buffer, 0, (int) Math.min(buffer.length, endIndex - startIndex + 1 - downloaded))) != -1) {
                raf.write(buffer, 0, len);
                downloaded += len;
            }
            raf.close();
            bis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}